import axios from "axios"
import { Notify } from "vant"
const env = process.env.NODE_ENV
import { handleData } from "../utils/handleData"
import Setting from "@/setting"

// axios.defaults.withCredentials = true; // 允许跨域携带cookie信息
// // 创建一个 axios 实例
// //   let _port = sessionStorage.getItem('UAP_ISC_PORT');
//   let _port = 33201;
// // console.log("传过来的端口号",_port);`
// const service = axios.create({
//  baseURL:
//     env === "development"
//       ? "/api"
//       : "http://192.168.3.30/:" + _port + "/api/ra/realasset-flc",
//   /*baseURL:
//     env === "development"
//       ? "/api"
//       : "http://127.0.0.1:" + _port + "/hqmismobilezcgl",*/
//   widthCredentials: true,
//   crossDomain: true,
//   timeout: 300000, // 请求超时时间
// });
// function geturlparam (url) {
//   if (!url) return;
//   let p = url.split('?')[1];
//   return p
// }

const service = axios.create({
  baseURL: Setting.apiBaseURL,
  widthCredentials: true,
  crossDomain: true,
  timeout: 30000 // 请求超时时间
})
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (Setting.codeMode === "uapRelease") {
      config.baseURL += sessionStorage.getItem("UAP_ISC_PORT")
    }
    let sign = ""
    let str = ""
    let salt = getRandomString()
    if (config.data && config.method != "get") {
      if (config.url.indexOf("?") > -1) {
        str = decodeURI(geturlparam(config.url))
      }
      let obj = {}
      if (config.data instanceof FormData) {
        // 表单提交
        let hasFile = false
        for (var [key, value] of config.data) {
          if (value instanceof File) {
            hasFile = true
            obj.file = value.fileName
          } else {
            obj[key] = value
          }
        }
        if (hasFile) {
          let arr = Object.keys(obj).sort()
          let sortObj = {}
          arr.forEach((item) => {
            sortObj[item] = obj[item]
          })
          str += JSON.stringify(sortObj) + salt
        } else {
          str += decodeURI(JSON.stringify(obj)) + salt
        }
      } else if (config.data instanceof Array) {
        // data值为数组
        str += JSON.stringify(config.data) + salt
      } else {
        for (var key in config.data) {
          if (config.data[key] instanceof File) {
          } else {
            obj[key] = config.data[key]
          }
        }
        str += JSON.stringify(obj) + salt
      }
    } else if (config.url.indexOf("?") > -1) {
      str = decodeURI(geturlparam(config.url)) + salt
    } else if (config.params) {
      for (let key in config.params) {
        str += key + "=" + config.params[key] + "&"
      }
      str = str ? decodeURI(str.slice(0, -1)) + salt : salt
    } else {
      str = salt
    }
    sign = SG_sm3encrypt(str)
    config.headers["sign"] = sign
    config.headers["salt"] = salt
    // 在请求发送之前做一些处理
    // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    // config.headers['X-Token'] = token;
    let token = sessionStorage.getItem("token") || ""
    let userid = sessionStorage.getItem("userid") || ""
    let corpid = JSON.parse(sessionStorage.getItem("userInfo")).custom.orgId || ""
    config.headers["igw-env"] = Setting.igwEnv // i国网环境标识
    config.headers["token"] = token
    config.headers["userid"] = userid
    config.headers["userId"] = userid
    config.headers["corpId"] = corpid
    // config.headers["userName"] = userName;
    return config
  },
  (error) => {
    // 发送失败
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // if (filterData(response.data)) {
    //   return false;
    // } else {
    const token = response.headers.token || ""
    const prevToken = sessionStorage.getItem("token") || ""
    if (!prevToken) {
      sessionStorage.setItem("token", token)
    }
    const dataAxios = response.data

    return handleData(dataAxios)
    // }
  },
  (error) => {
    sessionStorage.removeItem("statusCode")
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = "请求错误"
          break
        case 401:
          error.message = "未授权，请登录"
          break
        case 403:
          error.message = "拒绝访问"
          break
        case 404:
          error.message = `请求地址出错`
          break
        case 408:
          error.message = "请求超时"
          break
        case 500:
          error.message = "服务器内部错误"
          break
        case 501:
          error.message = "服务未实现"
          break
        case 502:
          error.message = "网关错误"
          break
        case 503:
          error.message = "服务不可用"
          break
        case 504:
          error.message = "网关超时"
          break
        case 505:
          error.message = "HTTP版本不受支持"
          break
        default:
          break
      }
      if (error.message) {
        Notify({ type: "warning", message: error.message })
      }
    }
    return Promise.reject(error)
  }
)
export default service
